<template>
  <div class="demo">
    <div>
      <input type="file" @change="submitUpload($event)">
    </div>
  </div>
</template>

<script>
import { upload } from '@/api/article';
import { Toast } from 'vant';
export default {
  data() {
    return {};
  },
  methods: {
    async submitUpload(e) {
      const blob = e.target.files[0];
      console.log(blob);
      const fileSize = blob.size; // 文件大小
      const fileName = blob.name; // 文件名
      // 每个文件切片大小定为1MB
      var sliceSize = 1 * 1024;
      // 文件大小限制为最大100MB，可根据需求修改
      var filesizes = 100 * 1024 * 1024;
      const that = this;
      // 计算文件切片总数
      const totalSlice = Math.ceil(fileSize / sliceSize);
      console.log(totalSlice);
      if (fileSize <= filesizes) {
        console.log('111111');
        // 循环上传
        for (let i = 0; i < totalSlice; i++) {
          console.log('2222222');
          const start = i * sliceSize;
          const chunk = blob.slice(start, Math.min(fileSize, start + sliceSize));
          const formData = new FormData();
          console.log('333333');
          formData.append('file', chunk);
          formData.append('name', fileName);
          formData.append('size', fileSize);
          formData.append('chunks', totalSlice);
          formData.append('chunk', i);
          console.log(formData);
          // 一个分片上传完成后再调用接口上传下一片
          const res = await upload(formData);
          if (res.code === 0) {
            this.progress = ((i + 1) / totalSlice).toFixed(1) * 100; // 控制进度条
            setTimeout(function() {
              if (i + 1 === totalSlice) {
                Toast('上传成功');
                that.$message({
                  message: '上传成功',
                  type: 'success'
                });
                return false;
              }
            }, 1000);
          } else {
            Toast('上传失败');
            return false;
          }
        }
      } else {
        Toast('文件大小超出1G');
        return false;
      }
    }
  }
};
</script>
